package com.waterai.service.impl;

import com.waterai.dao.UserDao;
import com.waterai.dto.UserDTO;
import com.waterai.entity.User;
import com.waterai.excel.UserExcel;
import com.waterai.service.UserService;
import com.waterai.tools.utils.PageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public PageData<UserDTO> all(Map<String, Object> params) {
        List<UserDTO> dtos = userDao.querySelectList(params);
        int count = userDao.queryListCount(params);
        return new PageData<>(count, dtos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setDelFlag('0');
        userDao.insert(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(User user) {
        user.setUpdateTime(new Date());
        user.setDelFlag('0');
        userDao.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 软删
        User user = userDao.selectById(id);
        user.setDelFlag('1');
        userDao.updateById(user);
    }

    @Override
    public List<UserDTO> queryByIds(String[] ids) {
        List<UserDTO> userDTOS = new ArrayList<>();
        if (ids.length == 0) {
            return userDao.querySelectList(new HashMap<>());
        }
        for (String id : ids) {
            User user = userDao.selectById(Long.parseLong(id));
            if (user != null) {
                UserDTO dto = new UserDTO();
                BeanUtils.copyProperties(user, dto);
                userDTOS.add(dto);
            }
        }
        return userDTOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSave(List<UserExcel> data) {
        List<UserExcel> haveId = new ArrayList<>();
        List<UserExcel> noID = new ArrayList<>();
        Date date = new Date();
        for (UserExcel datum : data) {
            datum.setCreateTime(date);
            datum.setUpdateTime(date);
            if (datum.getId() == null) {
                noID.add(datum);
            } else {
                haveId.add(datum);
            }
        }
        if (!haveId.isEmpty()) {
            userDao.importBatch(haveId);
        }
        if (!noID.isEmpty()) {
            userDao.importBatchNoId(noID);
        }
    }
}
